import 'reflect-metadata';
import { ColumnType } from '../db/ColumnType';
import { TableStruct, TableStructCache, IdCache } from '../db/TableStructCache';
import { AnnotationEnum } from './AnnotationEnum';

const TAG = "CJDBUtil"

export const Id = (v?: {
  columnName?: string,
  types: ColumnType,
  autoincrement?: boolean
}): PropertyDecorator => (target, primaryKey: string) => {
  let autoincrement = false
  let columnName = primaryKey
  let types: ColumnType
  if (v && v.types) {
    types = v.types
  } else {
    types = ColumnType.INTEGER
  }
  if (v && v.columnName) {
    columnName = v.columnName
  }
  if (types == ColumnType.INTEGER && autoincrement == undefined) {
    autoincrement = true
  }
  if (v && v.autoincrement != undefined) {
    autoincrement = v.autoincrement
  }
  if (v && v.types) {
    types = v.types
  }

  Reflect.defineMetadata(AnnotationEnum.IS_ID, true, target, primaryKey);
  Reflect.defineMetadata(AnnotationEnum.COLUMN, columnName, target, primaryKey);
  Reflect.defineMetadata(AnnotationEnum.TYPE, types, target, primaryKey);
  Reflect.defineMetadata(AnnotationEnum.AUTOINCREMENT, autoincrement, target, primaryKey);

  // ====================

  // CJLogUtil.info(TAG, "table cache has：" + TableStructCache.maps.has(target.constructor.name))
  if (!TableStructCache.structMaps.has(target.constructor.name)) {
    TableStructCache.structMaps.set(target.constructor.name, [])
  }
  let caches: Array<TableStruct> = TableStructCache.structMaps.get(target.constructor.name)
  caches.push({
    name: primaryKey,
    columnName: columnName,
    type: types,
    isId: true,
    autoincrement: autoincrement
  })

  let idtemp: IdCache = new IdCache()
  idtemp.idName = primaryKey
  idtemp.idColumnName = columnName
  idtemp.autoincrement = autoincrement
  TableStructCache.idMaps.set(target.constructor.name, idtemp)
  // CJLogUtil.info(TAG, "TableStructCache：" + JSON.stringify(caches))

}